import os
import logging
from django.http import JsonResponse
from django.views import View
import json
from pymysql import DatabaseError
from utils.qiniuyun import upload_img
from utils.relogin import LoginRequiredJSONMixin


QNYUN_URL = 'http://qsvra613q.hn-bkt.clouddn.com/'
# 个人中心
class UsercenterView(LoginRequiredJSONMixin,View):
    def get(self,request):
        user = request.user
        data = {
            'avatar_url':QNYUN_URL + str(user.avatar),
            'mobile': user.mobile,
            'name': user.username,
        }
        return JsonResponse({"errno":0,"errmsg":"ok","data":data})

from aijia.settings import BASE_DIR
# 个人头像
class UseravatarView(LoginRequiredJSONMixin,View):
    def post(self,request):
        # 1 接收数据
        avatar = request.FILES.get('avatar')
        # 2 验证参数
        if avatar is None:
            return JsonResponse({'errno':400,'errmsg':'没有图片'})
        # 3 保存图片路径
        file_path = os.path.join(BASE_DIR,'image/avatar')
        with open(file_path,'wb') as f:
            content = avatar.read()
            f.write(content)
        # 4 调用七牛云
        try:
            key = upload_img(str(avatar),file_path)
        except Exception:
            return JsonResponse({'errno':400,'errmsg':'图片上传失败'})
        # 5 保存头像
        request.user.avatar = key
        try:
            request.user.save()
        except Exception:
            return JsonResponse({'errno':400,'errmsg':'图片上传失败'})
        finally:
            # 删除图片文件
            # import time
            # time.sleep(5)
            os.remove(file_path)
        # 6 返回响应
        data = {
            'avatar_url':QNYUN_URL + key
        }
        return JsonResponse({'errno':0,'errmsg':'头像上传成功','data':data})

# 日志信息
logger = logging.getLogger('django')
# 用户名修改
class UsernameView(LoginRequiredJSONMixin,View):
    def put(self,request):
        # 1 获取数据
        data = json.loads(request.body.decode())
        # 2 提取参数name
        username = data.get('name')
        # 3 验证参数
        if username is None:
            return JsonResponse({'errno':400,'errmsg':'修改参数错误'})
        # 4 数据入库
        try:
            request.user.username = username
            request.user.save()
        except DatabaseError as e:
            logger.error(e)
            return JsonResponse({'errno':400,'errmsg':'数据保存失败'})
        # 5 返回响应
        return JsonResponse({'errno':0,'errmsg':'修改成功'})


# 用户实名认证
class UserauthView(LoginRequiredJSONMixin,View):
    def post(self,request):
        # 1 接收参数
        data_dict = json.loads(request.body.decode())
        # 2 提取参数
        real_name = data_dict.get('real_name')
        id_card = data_dict.get('id_card')
        # 3 验证参数
        if not all([real_name,id_card]):
            return JsonResponse({'errno':400,'errmsg':'参数不全请重新输入'})
        # 4 数据入库
        try:
            request.user.real_name = real_name
            request.user.id_card = id_card
            request.user.save()
        except DatabaseError as e:
            logger.error(e)
            return JsonResponse({'errno':400,'errmsg':'数据保存失败'})
        # 5 返回响应
        else:
            return JsonResponse({'errno':0,'errmsg':'认证成功'})


    # 判断是否实名认证
    def get(self,request):
        # 1 获取数据库信息
        user = request.user
        # 2 提取真实姓名和身份证信息
        real_name = user.real_name
        id_card = user.id_card
        # 3 判断是否有信息是否认证
        if not all([real_name,id_card]):
            return JsonResponse({'errno':400,'errmsg':'未认证'})
        # 4 返回数据
        data = {
            'real_name':real_name,
            'id_card':id_card
        }
        return JsonResponse({'errno':0,'errmsg':'认证成功','data':data})
